//  this library.
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/pages/tab/home.dart';
import 'package:hktk_app/pages/tab/mine.dart';
import 'package:hktk_app/pages/tab/question.dart';
import 'package:hktk_app/pages/tab/select.dart';
import 'package:hktk_app/pages/tab/study.dart';
import 'package:hktk_app/provider/chapter_state.dart';

import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/font_util.dart';

import 'package:hktk_app/util/screen_adapter_helper.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:provider/provider.dart';
import 'package:hktk_app/dao/login_dao.dart';

/// 底部导航器
class TabNavigator extends StatefulWidget {
  /// 控制进入时的默认页面
  final int pageIndex;
  final int subIndex;

  const TabNavigator({
    super.key,
    this.pageIndex = 0,
    this.subIndex = 0,
  });

  @override
  State<TabNavigator> createState() => _TabNavigatorState();
}

class _TabNavigatorState extends State<TabNavigator>
    with WidgetsBindingObserver {
  final GlobalKey _globalKey = GlobalKey();
  final GlobalKey<StudyPageState> studyKey= GlobalKey();

  late BuildContext _context;

  /// 控制器
  late PageController _controller;

  /// 打开的是第几个页面
  late int _currentIndex = 0;

  /// 接收监听器过来的对应id
  late String? _eventColumnId;

  /// 监听器
  late StreamSubscription<EventColumnsBuy> _eventColumn;

  /// 上次点击时间
  late DateTime _lastPressedAt;
  late int _subIndex;


  @override
  void initState() {
    super.initState();


    _subIndex = widget.subIndex;



    _controller = PageController(
      initialPage: widget.pageIndex, // 打开时的默认页面
      // initialPage: 0, // 打开时的默认页面
    );
    _currentIndex =  widget.pageIndex;
    _lastPressedAt = DateTime.now();
    _eventColumnId = null;

    // 监听首页过来的栏目购买通知
    _eventColumn = eventBus.on<EventColumnsBuy>().listen((event) {
      if (mounted) {
        // 将页面跳转至对应页面
        _controller.jumpToPage(1);
        setState(() {
          _eventColumnId = event.columnId;
          _currentIndex = 1;
        });
      }
    });

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      // 这里的渲染回调是在该组件所有渲染完成后，所以是在子组件渲染完成后才执行的,但是回调通知是先父组件，再子组件
      final RenderBox? renderBox =
          _globalKey.currentContext?.findRenderObject() as RenderBox?;
      ScreenHelper.bottomNavigationBarHeight = renderBox!.size.height;
    });
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
    _eventColumn.cancel();
  }

  @override
  Widget build(BuildContext context) {
    _context = context;
    LoginDao.initContext(_context);
    // 初始化跳转路由，供登录登出时使用
    // NavigatorUtil.initContext(context);
    return PopScope(
      child: _scaContent(),
      canPop: false,
      // onPopInvoked: _onPopInvoked,
      onPopInvokedWithResult: _onPopInvoked,
    );
  }

  // 是否退出系统判断
  void _onPopInvoked<T>(bool didPop, T? result) {
    if (didPop) {
      // 页面已经被弹出（例如 Navigator.pop 被调用）
      return;
    }

    if (_lastPressedAt == null ||
        DateTime.now().difference(_lastPressedAt!) > Duration(seconds: 1)) {
      // 第一次点击或超过1秒未点击
      _lastPressedAt = DateTime.now();
      ToastUtil.show(context: context, msg: "再按一次退出");
    } else {
      // 第二次点击且时间间隔小于1秒，退出App
      SystemNavigator.pop(); // 退出应用
    }
    // if (DateTime.now().difference(_lastPressedAt) >
    //     const Duration(seconds: 1)) {
    //   ToastUtil.show(context: _context, msg: "再按一次退出程序");
    //   _lastPressedAt = DateTime.now();
    // } else {
    //   Navigator.of(_context).pop();
    //
    // }
  }
  void changeIndex(int index,int subIndex) {
    _subIndex = subIndex;
    _currentIndex = index;
  }
  void changeState(){
    setState(() {

    });
  }
  /// 内容页面
  _scaContent() {
    return Scaffold(
      backgroundColor: Colors.white,
      // body: Container(),
      body: PageView(
        controller: _controller,
        physics: const NeverScrollableScrollPhysics(), // 禁用左右滚动
        children: [
          MyHomePage(
            parentController: _controller,
            changeIndex: changeIndex,
            changeState: changeState,
            studyKey: studyKey,
          ),

          // Container(),

          StudyPage(
            initTabIndex: _subIndex,
            key: studyKey,
          ),
          SelectPage(
            initTabIndex: _subIndex,
          ),
          MultiProvider(providers: [
            ChangeNotifierProvider(
              create: (context) => ChapterState(),
            ),
          ], child: QuestionPage()),
          const MinePage(),

          // const HomePage(),
          // PackagePage(
          //   columnId: _eventColumnId,
          // ),
          // StudyPage(),
          // QuestionPage(),
        ], // 页面内容
      ),
      bottomNavigationBar: BottomNavigationBar(
        key: _globalKey,
        type: BottomNavigationBarType.fixed,
        // 选中颜色
        fixedColor: colorBlue1,
        backgroundColor: colorWhite8,
        unselectedLabelStyle: FontUtil.fontBlack1(14),
        selectedLabelStyle: FontUtil.fontBlue1(14),
        currentIndex: _currentIndex,
        onTap: (index) {
          // 当前第几个tab被点击了
          _controller.jumpToPage(index);
          setState(() {
            _currentIndex = index;
            _eventColumnId = null;
          });
        },
        // 这里要超过3个tab才使用，要不然可能会导致显示不出来
        // type: BottomNavigationBarType.fixed,
        items: [
          _bottomItem(
            "首页",
            "images/tab/home_default.svg",
            "images/tab/home_select.svg",
            0,
          ),
          _bottomItem(
            "学习",
            "images/tab/icon_package_default.svg",
            "images/tab/icon_package_select.svg",
            1,
          ),
          _bottomItem(
            "选课",
            "images/tab/course_default.svg",
            "images/tab/course_select.svg",
            2,
          ),
          _bottomItem(
            "题库",
            "images/tab/question_default.svg",
            "images/tab/question_select.svg",
            3,
          ),
          _bottomItem(
            "我的",
            "images/tab/my_default.svg",
            "images/tab/my_select.svg",
            4,
          ),
        ],
      ),
    );
  }

  _bottomItem(
    String title,
    String iconUrl,
    String activeUrl,
    int index,
  ) {
    return BottomNavigationBarItem(
      backgroundColor: colorWhite8,
      icon: Container(
        margin: const EdgeInsets.all(1),
        child: SvgPicture.asset(
          iconUrl,
          width: 24,
          height: 24,
        ),
      ),
      activeIcon: Container(
        margin: const EdgeInsets.all(1),
        child: SvgPicture.asset(
          activeUrl,
          width: 24,
          height: 24,
        ),
      ),
      label: title,
    );
  }
}
